$(document).ready(function () {
    var pageTag = $("[name='pageTag']").val();
    $(".nav-item").removeClass("active");
    $("#" + pageTag).addClass("active");
    getOnShelfBooks(1, getMdPageSize());
    getOffShelfBooks(1, getSmPageSize());
    fetchCategoryList();
    
    $("#update-book").click(function (e) {
        if (editBookValidate()) {
            if (document.getElementById('edit-book-pname').files[0]) {
                var fileSize =  document.getElementById('edit-book-pname').files[0].size;
                if(fileSize>1024*1024*4){
                    alert('请上传不超过4M的图片');
                    return;
                }
            }
            

            var url = "../Handle/BookHandlerService.ashx?method=Modify_One_Book_Info";
            var price = $("#edit-book-price").val();
            if ("元" == price.charAt(price.length - 1)) {
                price = price.substring(0, price.length - 1);
            }

            var categoryTags = "";
            $(".edit-category-tag:checked").each(function(){ 
                categoryTags += $(this).val() + ","; 
            });
            categoryTags = categoryTags.substring(0, categoryTags.length-1);
    
            var data = {
                bookId: $("#edit-book-id").val(),
                bookName: $("#edit-book-name").val(),
                bookAuthor: $("#edit-book-author").val(),
                bookPress: $("#edit-book-press").val(),
                bookPrice: price,
                bookISBN: $("#edit-book-isbn").val(),
                bookPYM: $("#edit-book-PYM").val(),
                bookDesc: $("#edit-book-desc").val(),
                bookPname: $("#edit-book-pname-preview").attr("src"),
                bookCid: ("" == categoryTags)?"童话故事":categoryTags,
            };
            
            if (document.getElementById('edit-book-pname').files[0]) {
                var path = document.getElementById("edit-book-pname").value;
                if ($.trim(path) == "") { alert("请选择要上传的文件"); return; }

                var result_msg = "";
                $.ajaxFileUpload({
                    url: url,  //这里是服务器处理的代码
                    type: 'post',
                    secureuri: false, //一般设置为false
                    fileElementId: 'edit-book-pname', // 上传文件的id、name属性名
                    dataType: 'json', //返回值类型，一般设置为json、application/json
                    data: data, //传递参数到服务器
                    success: function (data) {
                        // console.log(data);
                        if (1 == data.MessageType) {
                            $('#EditModal').modal('hide');
                            $("#dialog-modal-label").text("图书信息修改成功！");
                            $("#DialogModal").modal("show");
                            getOffShelfBooks($("#off-shelf-pagination").pagination("getCurrentPage"), getMdPageSize());
                        }
                    }
                });
            } else {
                $.ajax({
                    type: "POST",
                    data: data,
                    url: url,
                    dataType: "json",
                    success: function (data) {
                        if (1 == data.MessageType) {
                            $('#EditModal').modal('hide');
                            $("#dialog-modal-label").text("图书信息修改成功！");
                            $("#DialogModal").modal("show");
                            getOffShelfBooks($("#off-shelf-pagination").pagination("getCurrentPage"), getMdPageSize());
                        }
                    }
                });
            }
        }
    });

    $("#fetch-douban-isbn-btn").on("click", function() {
        if (isbnFetchDataValidate()) {
            var ISBN = $("#fetch-douban-isbn-form #isbn").val();
            var url = "https://api.douban.com/v2/book/isbn/" + ISBN;
            // var url = "https://douban.uieee.com/v2/book/isbn/" + ISBN;
            //console.log(url);
            $.ajax({
                type: "GET",
                url: url,
                dataType: "jsonp",
                crossDomain: true,
                success: function (data) {
                    //console.log(data);
                    // console.log(removeCharInString(data.price));
                    $("#isbn-book-id").val();
                    $("#isbn-book-name").text(data.title);
                    $("#isbn-book-author").text(data.author[0]);
                    $("#isbn-book-press").text(data.publisher);
                    $("#isbn-book-price").text(removeCharInString(data.price));
                    $("#isbn-book-isbn").text(data.isbn13);
                    $("#isbn-book-PYM").text(data.pubdate);
                    $("#isbn-book-desc").text(data.summary);
                    $("#isbn-book-pname").attr("src", data.image);

                    $("#isbn-content").removeClass("hidden");
                    // console.log(data);
                    //console.log(JSON.stringify(data));
                    //$('#douban-book-data').html('<pre>' +
                    //JSON.stringify(data, null, 4) + '</pre>');
                }
            });
        }
    });

    $("#fetch-douban-name-btn").on("click", function() {
        if (nameFetchDataValidate()) {
            var bookName = $("#douban-book-name").val();
            var url = "https://api.douban.com/v2/book/search?q=" + bookName;
            $.ajax({
                type: "GET",
                url: url,
                dataType: "jsonp",
                crossDomain: true,
                success: function (dataSet) {
                    var data = dataSet["books"][0];
                    $("#name-book-id").val();
                    $("#name-book-name").text(data.title);
                    $("#name-book-author").text(data.author[0]);
                    $("#name-book-press").text(data.publisher);
                    $("#name-book-price").text(removeCharInString(data.price));
                    $("#name-book-isbn").text(data.isbn13);
                    $("#name-book-PYM").text(data.pubdate);
                    $("#name-book-desc").text(data.summary);
                    $("#name-book-pname").attr("src", data.image);

                    $("#name-content").removeClass("hidden");
                    //console.log(dataSet["books"][0]);
                    //console.log(JSON.stringify(data));
                    //$('#douban-book-data').html('<pre>' +
                    //JSON.stringify(data, null, 4) + '</pre>');
                }
            });
        }
    });
    
    $("#manual-add-book-btn").click(function (e) {
        if (manualAddBookValidate()) {
            // alert("success");
            var fileSize =  document.getElementById('manual-book-pname').files[0].size;
            if(fileSize>1024*1024*4){
                alert('请上传不超过4M的图片');
                return;
            }
            // console.log(fileSize);
            addBook("manual-");
        }
    });

    $("#name-add-book-btn").click(function (e) {
        addBook("name-");
    });
    
    $("#add-book-btn").click(function (e) {
        addBook("isbn-");
    });

    

    $(document)
        .on('click', '.thumbnail-img', function(e) {
            e.preventDefault();
            //alert($(this).attr("value"));
            window.open("Book.aspx?BID="+$(this).attr("value"), "_self");      
        })
        .on('click', '.unshelf-btn', function(){
            offShelfABook($(this).attr("value"));
        })
        .on('click', '.shelf-btn', function(){
            onShelfABook($(this).attr("value"));
        })
        .on('click', '.edit-btn', function(){
            var url = "../Handle/BookHandlerService.ashx?method=Get_One_Book_Info_From_BID";
            // alert($(this).attr("value"));
            $.ajax({
                type: "POST",
                data: {BID: $(this).attr("value")},
                url: url,
                dataType: "json",
                success: function (data) {
                    //console.log(data);
                    data = data.rows[0];
                    var categoryTags = data.cname.split(",");
                    for (var i = 0; i < categoryTags.length; i++) {
                       //categoryTags[i]
                        $(".edit-category-tag").each(function(){ 
                            if(categoryTags[i] == $(this).val()) {
                                $(this).attr("checked", "true");
                            }
                        });
                    }

                    $("#edit-book-id").val(data.BID);
                    $("#edit-book-name").val(data.Bname);
                    $("#edit-book-author").val(data.Author);
                    $("#edit-book-press").val(data.Press);
                    $("#edit-book-price").val(data.Price);
                    $("#edit-book-isbn").val(data.ISBN);
                    $("#edit-book-PYM").val(data.PYM);
                    $("#edit-book-desc").val(data.Descript);
                    $("#edit-book-pname-preview").attr("src", data.Pname);
                    document.getElementById("edit-book-pname").value = "";
                    $("#EditModal").modal("show");
                }
            });
        });
});

function isbnFetchDataValidate() {
    return $("#fetch-douban-isbn-form").validate({
        errorClass: "warning",
        errorPlacement: function(error, element) {
            if (element.is(":checkbox")){  
                error.insertAfter(element.parent().parent());
            }else{  
                error.insertAfter(element.parent()); 
            }  
        }, 
        rules: {
            isbn: {
                required: true,
                minlength: 13,
                maxlength: 13,
                digits: true
            },
            isbnCategoryTag: "required"
        },
        messages: {
            isbn: {
                required: "ISBN不能为空",
                minlength: "ISBN应该是13位数字",
                maxlength: "ISBN应该是13位数字",
                digits: "ISBN应该为数字"
            },
            isbnCategoryTag: "请选择至少一个分类"
        }
    }).form();
}

function nameFetchDataValidate() {
    return $("#fetch-douban-name-form").validate({
        errorClass: "warning",
        errorPlacement: function(error, element) {
            if (element.is(":checkbox")){  
                error.insertAfter(element.parent().parent());
            }else{  
                error.insertAfter(element.parent()); 
            }  
        },  
        rules: {
            doubanBookName: {
                required: true,
                minlength: 2,
            },
            nameCategoryTag: "required"

        },
        messages: {
            doubanBookName: {
                required: "书名不能为空",
                minlength: "书名最小长度不小于2",
            },
            nameCategoryTag: "请选择至少一个分类"
        },
    }).form();
}

function manualAddBookValidate() {
    return $("#add-book-manual-form").validate({
        errorClass: "warning",
        errorPlacement: function(error, element) {
            if (element.is(":checkbox")){  
                error.insertAfter(element.parent().parent());
            }else{
                //element.addClass("inputborder");
                error.insertAfter(element.addClass("inputborder")); 
            }  
        }, 
        wrapper: "p",
        rules: {
            manualBookName: {
                required: true,
                minlength: 2,
            },
            manualBookAuthor: {
                required: true,
                minlength: 2,
            },
            manualBookPress: "required",
            manualBookPrice: {
                required: true,
                number:true,
            },
            manualBookISBN: {
                required: true,
                minlength: 13,
                maxlength: 13,
                digits: true
            },
            manualBookPYM: {
                required: true,
                date: true,
            },
            file1: {
                required: true,
                accept: "image/*",
            },
            manualBookDesc: {
                required: true,
                minlength: 50,
            },
            manualCategoryTag: "required",
        },
        messages: {
            manualBookName: {
                required: "书名不能为空",
                minlength: "书名最小长度不小于2",
            },
            manualBookAuthor: {
                required: "作者不能为空",
                minlength: "作者最小长度不小于2",
            },
            manualBookPress: "出版社不能为空",
            manualBookPrice: {
                required: "价格不能为空",
                number: "价格应该为数字",
            },
            manualBookISBN: {
                required: "ISBN不能为空",
                minlength: "ISBN应该是13位数字",
                maxlength: "ISBN应该是13位数字",
                digits: "ISBN应该为数字"
            },
            manualBookPYM: {
                required: "出版日期不能为空",
                date: "请输入合法日期",
            },
            file1: {
                required: "封面图片不能为空",
                accept: "请上传图片！"
            },
            manualBookDesc: {
                required: "书本描述不能为空",
                minlength: "描述文字不少于50个字",
            },
            manualCategoryTag: {
                required: "需要选择类别",
            },
        }
    }).form();
}

function editBookValidate() {
    return $("#edit-book-form").validate({
        errorClass: "warning",
        errorPlacement: function(error, element) {
            if (element.is(":checkbox")){  
                error.insertAfter(element.parent().parent());
            }else{  
                error.insertAfter(element); 
            }  
        }, 
        wrapper: "p",
        rules: {
            editBookName: {
                required: true,
                minlength: 2,
            },
            editBookAuthor: {
                required: true,
                minlength: 2,
            },
            editBookPress: "required",
            editBookPrice: {
                required: true,
                number:true,
            },
            editBookISBN: {
                required: true,
                minlength: 13,
                maxlength: 13,
                digits: true
            },
            editBookPYM: {
                required: true,
                date: true,
            },
            file1: {
                accept: "image/*"
            },
            editBookDesc: {
                required: true,
                minlength: 50,
            },
            editCategoryTag: "required",
        },
        messages: {
            editBookName: {
                required: "书名不能为空",
                minlength: "书名最小长度不小于2",
            },
            editBookAuthor: {
                required: "作者不能为空",
                minlength: "作者最小长度不小于2",
            },
            editBookPress: "出版社不能为空",
            editBookPrice: {
                required: "价格不能为空",
                number: "价格应该为数字",
            },
            editBookISBN: {
                required: "ISBN不能为空",
                minlength: "ISBN应该是13位数字",
                maxlength: "ISBN应该是13位数字",
                digits: "ISBN应该为数字"
            },
            editBookPYM: {
                required: "出版日期不能为空",
                date: "请输入合法日期",
            },
            file1: {
                accept: "请上传图片！"
            },
            editBookDesc: {
                required: "书本描述不能为空",
                minlength: "描述文字不少于50个字",
            },
            editCategoryTag: {
                required: "需要选择类别",
            },
        }
    }).form();
}

function addBook(approach) {
    var url = "../Handle/BookHandlerService.ashx?method=Add_New_Book";
    
    var categoryTags = "";
    $("."+approach+"category-tag:checked").each(function(){ 
        categoryTags += $(this).val() + ","; 
    });
    categoryTags = categoryTags.substring(0, categoryTags.length-1);

    var price = $("#"+approach+"book-price").text()?$("#"+approach+"book-price").text():$("#"+approach+"book-price").val();
    price = price?price:"0";
    //alert(price);
    if ("元" === price.charAt(price.length - 1)) {
        price = price.substring(0, price.length - 1);
    }
    var data = {
        bookName: $("#"+approach+"book-name").text()?$("#"+approach+"book-name").text():$("#"+approach+"book-name").val(),
        bookAuthor: $("#"+approach+"book-author").text()?$("#"+approach+"book-author").text():$("#"+approach+"book-author").val(),
        bookPress: $("#"+approach+"book-press").text()?$("#"+approach+"book-press").text():$("#"+approach+"book-press").val(),
        bookPrice: price,
        bookISBN: $("#"+approach+"book-isbn").text()?$("#"+approach+"book-isbn").text():$("#"+approach+"book-isbn").val(),
        bookPYM: $("#"+approach+"book-PYM").text()?$("#"+approach+"book-PYM").text():$("#"+approach+"book-PYM").val(),
        bookDesc: $("#"+approach+"book-desc").text()?$("#"+approach+"book-desc").text():$("#"+approach+"book-desc").val(),
        bookPname: $("#"+approach+"book-pname").attr("src")?$("#"+approach+"book-pname").attr("src"):$("#"+approach+"book-pname").val(),
        bookCid: ("" == categoryTags)?"童话故事":categoryTags,
    };
// console.log(data);
    if ("manual-" == approach) {
        var path = document.getElementById("manual-book-pname").value;
        if ($.trim(path) == "") { alert("请选择要上传的文件"); return; }
        data.bookPname = "";
        var result_msg = "";
        $.ajaxFileUpload({
            url: url,  //这里是服务器处理的代码
            type: 'post',
            secureuri: false, //一般设置为false
            fileElementId: 'manual-book-pname', // 上传文件的id、name属性名
            dataType: 'json', //返回值类型，一般设置为json、application/json
            data: data, //传递参数到服务器
            success: function (data) {
                console.log(data);
                $("#dialog-modal-label").text(data.MessageContent);
                $("#DialogModal").modal("show");
                if (1 == data.MessageType) {
                    $("#manual-book-name").val("");
                    $("#manual-book-author").val("");
                    $("#manual-book-press").val("");
                    $("#manual-book-price").val("");
                    $("#manual-book-isbn").val("");
                    $("#manual-book-PYM").val("");
                    $("#manual-book-desc").val("");
                    document.getElementById("manual-book-pname").value = "";
                    fetchCategoryList();
                    getOnShelfBooks(1, getMdPageSize());
                }
            }
        });
    } else {
        $.ajax({
            type: "POST",
            data: data,
            url: url,
            dataType: "json",
            success: function (data) {
                console.log(data);
                $("#dialog-modal-label").text(data.MessageContent);
                $("#DialogModal").modal("show");
                if (1 == data.MessageType) {
                    $("#isbn-content").addClass("hidden");
                    $("#name-content").addClass("hidden");
                    fetchCategoryList();
                    getOnShelfBooks(1, getMdPageSize());
                }
            }
        });
    }
    
}

function offShelfABook(BID) {
    $.ajax({
        type: "GET",
        data: { BID: BID},
        url: "../Handle/BookHandlerService.ashx?method=Shelf_One_Book_From_BID",
        dataType: "json",
        success: function (data) {
            //console.log(data);
            if (1 == data.MessageType) {
                $("#dialog-modal-label").text("图书下架成功！");
                $("#DialogModal").modal("show");
                getOnShelfBooks(1, getMdPageSize());
                getOffShelfBooks(1, getSmPageSize());
            }
        }
    });
}

function onShelfABook(BID) {
    $.ajax({
        type: "GET",
        data: { BID: BID},
        url: "../Handle/BookHandlerService.ashx?method=Shelf_One_Book_From_BID",
        dataType: "json",
        success: function (data) {
            // console.log(data);
            if (1 == data.MessageType) {
                $("#dialog-modal-label").text("图书上架成功！");
                $("#DialogModal").modal("show");
                getOnShelfBooks(1, getMdPageSize());
                getOffShelfBooks(1, getSmPageSize());
            }
        }
    });
}

function getOnShelfBooks(pageIndex, pageSize) {
    $.ajax({
        type: "GET",
        data: { PageIndex: pageIndex, PageSize: pageSize },
        url: "../Handle/BookHandlerService.ashx?method=Get_ON_Shelf_Books_From_UID",
        dataType: "json",
        success: function (data) {
            //console.log(data.rows);
            $("#book-list").html(getBookListOutputHtml(data.rows, "shelf", 6, 3));
            //$("#on-shelf-book-list-pagination").html(getPaginationBtnOutputHtml(data.PageCount, pageIndex, "on-shelf-pagination-btn"));
            $("#on-shelf-pagination").pagination({
                items: data.RecordCount,
                itemsOnPage: pageSize,
                currentPage: pageIndex,
                displayedPages: 3,
                onPageClick: changeOnShelfBookPage,
                edges: 0,
                prevText: "<",
                nextText: ">",
                cssStyle: 'light-theme',
            });
        }
    });
}

function changeOnShelfBookPage() {
    getOnShelfBooks($("#on-shelf-pagination").pagination("getCurrentPage"), getMdPageSize());
}

function getOffShelfBooks(pageIndex, pageSize) {
    $.ajax({
        type: "GET",
        data: { PageIndex: pageIndex, PageSize: pageSize },
        url: "../Handle/BookHandlerService.ashx?method=Get_Off_Shelf_Books_From_UID",
        dataType: "json",
        success: function (data) {
            // console.log(data);
            $("#unshelf-book-list").html(getBookListOutputHtml(data.rows, "unshelf", 6, 6));
            //$("#off-shelf-book-list-pagination").html(getPaginationBtnOutputHtml(data.PageCount, pageIndex, "off-shelf-pagination-btn"));
            $("#off-shelf-pagination").pagination({
                items: data.RecordCount,
                itemsOnPage: pageSize,
                currentPage: pageIndex,
                displayedPages: 3,
                onPageClick: changeOffShelfBookPage,
                edges: 0,
                prevText: "<",
                nextText: ">",
                cssStyle: 'light-theme',
            });
        }
    });
}
function changeOffShelfBookPage() {
    getOffShelfBooks($("#off-shelf-pagination").pagination("getCurrentPage"), getMdPageSize());
}
//style='border: 0 none;margin-bottom: 2px;margin-top: 2px;'
function getBookListOutputHtml(items, shelfState, smItemWidthPerline, mdItemWidthPerline) {
    var outputHtml = "";
    var outputClass = "col-xs-" + smItemWidthPerline + " col-md-" + mdItemWidthPerline;
    
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
    
        var footElement = "";
        if ("0" == item["Flag"]) {
            if ("0" == item["Cstatus"]) {
                footElement = "<a class='btn btn-xs btn-danger unshelf-btn' value='"+item["BID"]+"' >下架</a>";
            } else {
                footElement = "<p style='margin-bottom:0px;height:22px;'><small>已借出</small></p>";
            }
        } else if ("1" == item["Flag"]) {
            footElement = "<a class='btn btn-xs btn-info edit-btn' value='"+item["BID"]+"'>编辑</a> "+
                            " <a href='#' class='btn btn-xs btn-danger shelf-btn' value='"+item["BID"]+"'>上架</a>";
        }

        //var dataContent = "<p><small>" + item["Author"] + " / " + item["PYM"] + " / " + item["Press"] + "</small></p><small>" + subStrToLimitLength(item["Descript"], 150) + "</small>";
        //var dataContent = "<p><small>" + item["Author"] + " / " + item["PYM"] + " / " + item["Press"] + "</small></p>";
        outputHtml += "<div class='" + outputClass + "' style='padding-left:10px;padding-right:10px;padding-bottom:10px;'>" +
        "<div class='thumbnail' style='border: 0 none;padding:0px;'>" +
            "<img src='" + item["Pname"] + 
            "' style='width: 147px;height: 148px;' alt='图书封面'  title='" + item["Bname"] +
            "' class='thumbnail-img img-responsive  center-block col-md-10 col-xs-12' value='"+item["BID"]+"' />" +
            "<div class='caption col-md-12 col-xs-12' style='padding-top:0px;padding-right:0px;padding-bottom:0px'>" +
            "<p>" + subStrToLimitLength(item["Bname"], 6) + "</p>" +
            "<!--<p><small>" + subStrToLimitLength(item["Author"], 10) + "</small></p>-->" +
            footElement+
            "</div>" +
        "</div>" +
        "</div>";
    }
    return outputHtml;
}

function fetchCategoryList() {
    $.ajax({
        type: "GET",
        url: "../Handle/OtherHandlerService.ashx?method=Get_ALL_Category",
        dataType: "json",
        success: function (data) {
            // console.log(data.rows);

            $('#isbn-category-checkbox-list').html(buildCategoryCheckboxList(data.rows, "isbnCategoryTag", "isbn-category-tag"));
            $('#name-category-checkbox-list').html(buildCategoryCheckboxList(data.rows, "nameCategoryTag", "name-category-tag"));
            $('#manual-category-checkbox-list').html(buildCategoryCheckboxList(data.rows, "manualCategoryTag", "manual-category-tag"));
            $('#edit-category-checkbox-list').html(buildCategoryCheckboxList(data.rows, "editCategoryTag", "edit-category-tag"));
        }
    });
    return "";
}

function buildCategoryCheckboxList(items, checkboxName, checkboxClass) {
    var outputHtml = "<div>";
    for (var i = 0; i < items.length; i++) {
        outputHtml += "<label class='col-md-4' style='padding-left:0;padding-right:0'><input type='checkbox' class='"+checkboxClass +" category-tag' name='"+checkboxName+"' value='"+items[i]["Cname"]+"'>"+items[i]["Cname"]+"</label>";
    }
    outputHtml += "</div>";
    //console.log(outputHtml);
    return outputHtml;
}

function getMdPageSize() {
    return 8;
}

function getSmPageSize() {
    return 8;
}

function removeCharInString(str){
    var reg = /[a-zA-Z\s*]/g;
    return str.replace(reg,"");
}